package com.platform.modules.sys.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.pagehelper.util.StringUtil;
import com.platform.common.annotation.SysLog;
import com.platform.common.enumstatus.AptitudeEnum;
import com.platform.common.enumstatus.SystemEnum;
import com.platform.common.page.PageUtil;
import com.platform.common.utils.RestResponse;
import com.platform.modules.prj.entity.PrjProjectEntity;
import com.platform.modules.prj.service.PrjProjectService;
import com.platform.modules.sys.entity.SysDictEntity;
import com.platform.modules.sys.entity.SysDictGroupEntity;
//import com.platform.modules.prj.service.PrjSelectionService;
import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.entity.SysOrgUserEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysDictGroupService;
import com.platform.modules.sys.service.SysDictService;
import com.platform.modules.sys.service.SysOrgService;
import com.platform.modules.sys.service.SysOrgUserService;
import com.platform.modules.sys.service.SysUserService;

/**
 * 组织机构Controller
 *
 * @author 肖亮
 */
@Api(tags = "SysOrgController|组织机构")
@RestController
@RequestMapping("sys/org")
public class SysOrgController extends AbstractController {
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgUserService sysOrgUserService;
    //@Autowired
    //private PrjSelectionService prjSelectionService;
    @Autowired
    private PrjProjectService prjProjectService;

    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private SysDictGroupService sysDictGroupService;
    

    /**
     * 1、查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @ApiOperation(value = "查看组织机构列表", notes = "查看组织机构列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orgName", value = "机构名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "parentNo", value = "上级机构", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "orgType", value = "机构级别", dataType = "String")
    })
    @PostMapping("/queryAll")
    //@RequiresPermissions("sys:org:list")
    public RestResponse queryAll(String orgName, String parentNo, String orgType) {

        Map<String, Object> params = new HashMap<String, Object>();
	        params.put("orgName", orgName);
	        params.put("parentNo", parentNo);
	        params.put("orgType", orgType);
        List<SysOrgEntity> list = sysOrgService.queryAll(params);
        return RestResponse.success().put("list", list);
    }
    
    
    /**
     * wangLc 2019-8-6
     * (1部级2.厅级3处级4科级5区级
     */
    @ApiOperation(value = "申报时查询机构", notes = "申报时查询机构")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orgType", value = "机构类型", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "orgLevel", value = "机构级别", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "prjId", value = "项目Id", dataType = "String")
    })
    @PostMapping("/decOrg")
    public RestResponse decOrg(String orgType, String orgLevel, String prjId) {

    	if(StringUtils.isBlank(orgType)){
    		return RestResponse.error("请传入正确的机构类型");
    	}
    	if(StringUtils.isBlank(orgLevel)){
    		return RestResponse.error("请传入正确的机构级别");
    	}

    	//查询项目信息
    	PrjProjectEntity prjProjectEntity = prjProjectService.getById(prjId);
    	if(prjProjectEntity != null){
    		 Map<String, Object> params = new HashMap<String, Object>();
    		    params.put("orgType", orgType);
		        params.put("orgLevel", orgLevel);
    		String provinceNum = prjProjectEntity.getProvinceNum(); //省
    		String cityNum = prjProjectEntity.getCityNum();         //市
    		String countyNum = prjProjectEntity.getCountyNum();     //县
    		if("1".equals(orgLevel)){        //部级
    			
    		}else if("2".equals(orgLevel)){  //厅级
    			params.put("provinceNo", provinceNum);
    		}else if("3".equals(orgLevel)){  //市级
    			params.put("cityNo", cityNum);
    		}else if("4".equals(orgLevel)){   //县级
    			params.put("countyNo", countyNum);
    		}
    		 List<SysOrgEntity> list = sysOrgService.queryAll(params);
    		 
    		 SysOrgEntity sysOrgEntity = null;
    		 if(list != null && list.size()>0){
    			 sysOrgEntity = list.get(0);
    		 }
 	        return RestResponse.success().put("org", sysOrgEntity);
    	}else{
    		return RestResponse.error("请传入正确的项目Id");
    	}
    }
    
    
    
    /**
     * 批量注册单位测试用
     */
    @ApiOperation(value = "批量注册单位测试用", notes = "批量注册单位测试用")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orgName", value = "机构名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "parentNo", value = "上级机构", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "orgType", value = "机构级别", dataType = "String")
    })
    @PostMapping("/addOrgPam")
    public RestResponse addOrgPam() {
    	
//    	
//    	for(int ){
//    		   APTITUDE_INDUSTRY   ORG_REGIST_TYPE
    	
//    	APTITUDE_SPECIALITY
//    	}
    	
    	for(int i=1;i<15;i++){
    		String orgName = "";
    		String name = "";
    		String creditCode = "";
    		String cityNo = "";
    		if(i<10){
    			cityNo = "0"+1;
    			creditCode = "450"+i+"00000000";
    		}else{
    			cityNo = ""+i;
    			creditCode = "45"+i+"00000000";
    		}
    		if(i==1){
    			name = "南宁";
    		}else if(i==2){
    			name = "柳州";
    		}else if(i==3){
    			name = "桂林";
    		}else if(i==4){
    			name = "梧州";
    		}else if(i==5){
    			name = "北海";
    		}else if(i==6){
    			name = "防城港";
    		}else if(i==7){
    			name = "钦州";
    		}else if(i==8){
    			name = "贵港";
    		}else if(i==9){
    			name = "玉林";
    		}else if(i==10){
    			name = "百色";
    		}else if(i==11){
    			name = "贺州";
    		}else if(i==12){
    			name = "河池";
    		}else if(i==13){
    			name = "来宾";
    		}else if(i==14){
    			name = "崇左";
    		}
    		
    		orgName = name+"市监管单位";
    		
    		SysOrgEntity sysOrgEntity = new SysOrgEntity();
    		sysOrgEntity.setProvinceNo("45");
    		sysOrgEntity.setCityNo(cityNo);
    		sysOrgEntity.setOrgLevel(3);
    		sysOrgEntity.setOrgType("5");
    		sysOrgEntity.setOrgLinkMailbox("931826598@qq.com");
    		sysOrgEntity.setStatus("2");
    		sysOrgEntity.setCreditCode(creditCode);
    		sysOrgEntity.setOrgName(orgName);
    		sysOrgEntity.setCreateUserId("1");
    		sysOrgEntity.setCreateTime(new Date());
    		sysOrgService.save(sysOrgEntity);
    		
    		SysUserEntity sysUserEntity = new SysUserEntity();
    		sysUserEntity.setUserName(creditCode);
    		sysUserEntity.setRealName(orgName);
    		sysUserEntity.setUserCard(creditCode);
    		sysUserEntity.setStatus("2");
    		sysUserEntity.setCreateUserId("1");
    		sysUserEntity.setCreateTime(new Date());
    	}
    	
    	
        return RestResponse.success();
    }
    
    

    /**
     * 查询所有机构列表
     */
    @ApiOperation(value = "查看组织机构列表-分页", notes = "查看组织机构列表-分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "currPage", value = "当前页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "limit", value = "分页步数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "orgName", value = "机构名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "creditCode", value = "社会统一信用代码", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "parentNo", value = "上级机构", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "parentName", value = "上级机构名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "orgType", value = "企业类型", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "企业状态", dataType = "String")
    })
    @PostMapping("/list")
    //@RequiresPermissions("sys:org:list")
    public RestResponse list(Integer currPage, Integer limit, String orgName, String parentNo, String orgType,String creditCode,String status,String parentName) {

        Map<String, Object> params = new HashMap<String, Object>();
        
        // status 表示 审核已通过（包括 启用和禁用）
        if("5".equals(status)){
        	List<String> statusPams = new ArrayList<String>();
        	statusPams.add("2");
        	statusPams.add("3");
        	params.put("statusPams", statusPams);
        }else{
        	params.put("status", status);
        }
        if("0".equals(status) || "1".equals(status)){
        	params.put("sidx", "O.CREATE_TIME");
			params.put("asc", false);
        }else if("2".equals(status) || "4".equals(status) || "5".equals(status)){
        	params.put("sidx", "W.AUDIT_TIME");
			params.put("asc", false);
        }
    	
        params.put("orgName", orgName);
        params.put("parentNo", parentNo);
        params.put("orgType", orgType);
        params.put("parentName", parentName);
        params.put("creditCode", creditCode);
        params.put("page", PageUtil.getCurrPage(currPage));
        params.put("limit", PageUtil.getLimit(limit));
        IPage page = sysOrgService.queryPage(params);
        return RestResponse.success().put("page", page);
    }

    @ApiOperation(value = "根据区ID查询监管机构列表-分页", notes = "根据区ID查询监管机构列表-分页")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "currPage", value = "当前页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "limit", value = "分页步数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "orgName", value = "机构名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "countyNo", value = "区县ID", dataType = "String")
    })
    @PostMapping("/countyOrglist")
    public RestResponse countyOrglist(Integer currPage, Integer limit, String orgName, String countyNo) {

        Map<String, Object> params = new HashMap<String, Object>();
	        params.put("orgName", orgName);
	        params.put("orgType", SystemEnum.orgType.JGDW.getKey()); //监管部门
	        params.put("countyNo", countyNo);
	        params.put("page", PageUtil.getCurrPage(currPage));
	        params.put("limit", PageUtil.getLimit(limit));
        IPage page = sysOrgService.queryPage(params);
        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param orgNo 主键
     * @return RestResponse
     */
    @ApiOperation(value = "根据主键查询组织机构详情", notes = "根据主键查询组织机构详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orgName", value = "机构名称", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "parentNo", value = "上级机构", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "orgType", value = "机构级别", dataType = "String")
    })
    @PostMapping("/info/{orgNo}")
    //@RequiresPermissions("sys:org:info")
    public RestResponse info(@PathVariable("orgNo") String orgNo) {
        SysOrgEntity sysOrg = sysOrgService.getById(orgNo);

        return RestResponse.success().put("org", sysOrg);
    }
    
    
    /**
     * 根据主键查询详情
     *
     * @param orgNo 主键
     * @return RestResponse
     */
    @ApiOperation(value = "根据主键查询组织机构详情", notes = "根据主键查询组织机构详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orgNo", value = "单位No", dataType = "String")
    })
    @PostMapping("/getOrgInfomation")
    public RestResponse getOrgInfomation(String orgNo) {
        SysOrgEntity sysOrg = sysOrgService.getById(orgNo);
        Map<String, Object> params = new HashMap<String, Object>();
        	params.put("accountType", "1");
        	params.put("orgNo", orgNo);
        
          List<SysUserEntity> list = sysUserService.queryUserByOrgNo(params);
	        if(list != null && list.size()>0){
	        	sysOrg.setUserCard(list.get(0).getUserCard());
	        	sysOrg.setUserName(list.get(0).getUserName());
	        	sysOrg.setRealName(list.get(0).getRealName());
	        }
        
        return RestResponse.success().put("org", sysOrg);
    }

	/**
	 * 资质企业列表（至少有一项通过资质的企业）
	 * @param sysOrg
	 * @return RestResponse
	 */
	@ApiOperation(value = "资质企业列表（至少有一项通过资质的企业）", notes = "资质企业列表（至少有一项通过资质的企业）")
	@SysLog("资质企业列表（至少有一项通过资质的企业）")
	@PostMapping("/aptitudeOrgList")
	public RestResponse aptitudeOrgList() {
		Map<String, Object> params = new HashMap<String, Object>();
			params.put("aptitudeStatus", AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
			params.put("status", AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
		IPage page = sysOrgService.queryPage(params);
		return RestResponse.success().put("page", page);
	}
	
	/**
	 * 随机抽取三家有资质审图机构(如果够三家情况下)
	 * @param sysOrg
	 * @return RestResponse
	 */
	 @ApiImplicitParams({
	     @ApiImplicitParam(paramType = "query", name = "decId", value = "报审ID", dataType = "String"),
	     @ApiImplicitParam(paramType = "query", name = "prjId", value = "项目ID", dataType = "String")
	 })
	@ApiOperation(value = "随机抽取三家有资质审图机构", notes = "随机抽取三家有资质审图机构")
	@SysLog("随机抽取三家有资质审图机构")
	@PostMapping("/randomAptitudeOrg")
	public RestResponse randomAptitudeOrg(String decId,String prjId) {
		
		String orgNo = "";
		SysUserEntity  user = this.getUser();
		if(user != null && user.getUserId() != null){
			SysUserEntity sysUserEntity = sysUserService.getById(user.getUserId());
			if(sysUserEntity != null && SystemEnum.accountType.ORG.getKey().equals(sysUserEntity.getAccountType())){
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("userId", sysUserEntity.getUserId());
				List<SysOrgUserEntity> orgUserList = sysOrgUserService.queryAll(params);
				if(orgUserList !=null && orgUserList.size()>0){
					orgNo = orgUserList.get(0).getOrgNo();         //获取当前登陆企业账号所属单位id
				}
			}
		}

		Map<String, Object> params = new HashMap<String, Object>();
		    params.put("orgType", SystemEnum.orgType.STDW.getKey());
			params.put("aptitudeStatus", AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
			params.put("status", AptitudeEnum.aptitudeStatus.YBSYPZ.getKey());
//		List<SysOrgEntity> list = sysOrgService.randomAptitudeOrg(params,orgNo,decId,prjId);
		List<SysOrgEntity> list = null;//prjSelectionService.randomAptitudeOrg(params,orgNo,decId,prjId);
//			PrjDeclareEntity prjDeclareEntity = prjDeclareService.getById(decId);   //查询此申报
//			List<SysOrgEntity> list = prjSelectionService.randomAptitudeOrg(prjDeclareEntity);
		return RestResponse.success().put("list", list);
	}
	 
	   /**
		 * 获取当前登陆企业账号单位信息
		 * @param sysOrg
		 * @return RestResponse
		 */
		 @ApiImplicitParams({
		     @ApiImplicitParam(paramType = "query", name = "status", value = "人员状态", dataType = "String")
		 })
		@ApiOperation(value = "获取当前登陆企业账号单位信息", notes = "获取当前登陆企业账号单位信息")
		@SysLog("获取当前登陆企业账号单位信息")
		@PostMapping("/getMyOrg")
		public RestResponse getMyOrg(String status) {
			
			  String orgNo = "";
			  SysUserEntity  user = this.getUser();
			if(user != null && user.getUserId() != null){
				SysUserEntity sysUserEntity = sysUserService.getById(user.getUserId());
				if(sysUserEntity != null && SystemEnum.accountType.ORG.getKey().equals(sysUserEntity.getAccountType())){
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("userId", sysUserEntity.getUserId());
					List<SysOrgUserEntity> orgUserList = sysOrgUserService.queryAll(params);
					if(orgUserList !=null && orgUserList.size()>0){
						orgNo = orgUserList.get(0).getOrgNo();         //获取当前登陆企业账号所属单位id
						
						SysOrgEntity sysOrgEntity =sysOrgService.getById(orgNo);
						Map<String, Object> userParams = new HashMap<String, Object>();
							userParams.put("orgNo", orgNo);
							userParams.put("status", status);
							
			            
						if(sysOrgEntity != null){
							//查询上级单位名称
							String parentNo = sysOrgEntity.getParentNo();
							SysOrgEntity parentOrgEntity =sysOrgService.getById(parentNo);
							if(parentOrgEntity != null){
								sysOrgEntity.setParentName(parentOrgEntity.getOrgName());
							}
							
							String checkOrgNo = sysOrgEntity.getCheckOrg();
							if(StringUtils.isNotBlank(checkOrgNo)){
								SysOrgEntity checkOrg =sysOrgService.getById(checkOrgNo);
								if(checkOrg != null){
									sysOrgEntity.setCheckOrgName(checkOrg.getOrgName());
								}
							}
							
							
							
						}
						//单位下所有人员信息
						List<SysUserEntity> userList =	sysUserService.queryUserByOrgNo(userParams);
						sysOrgEntity.setUserList(userList);
						sysOrgEntity.setUserCard(user.getUserCard());
						sysOrgEntity.setUserName(user.getUserName());
						return RestResponse.success().put("sysOrgEntity", sysOrgEntity);	
					}
				}else{
					return RestResponse.error("请使用企业账号");
				}
			}
			return RestResponse.error("数据有误");
		}
	
    /**
     * 保存
     *
     * @param sysOrg sysOrg
     * @return RestResponse
     */
    @ApiOperation(value = "保存机构", notes = "保存机构")
    @SysLog("保存机构")
    @PostMapping("/save")
    @RequiresPermissions("sys:org:save")
    public RestResponse save(SysOrgEntity sysOrg,HttpServletRequest request) {
        SysUserEntity user = getUser();
        if(sysOrg !=null && StringUtils.isNotBlank(sysOrg.getUserName())){
        	SysUserEntity sysUserEntity = sysUserService.queryByUserName(sysOrg.getUserName());
        	if(sysUserEntity !=null){
        		return RestResponse.error("用户登录名不能重复");
        	}
        }
        sysOrgService.addOrg(sysOrg, user,request);
//        mailService.sendMail(sysOrg.getOrgLinkMailbox(), "系统用户注册验证邮件", "");

        return RestResponse.success();
    }

    /**
     * 修改
     *
     * @param sysOrg sysOrg
     * @return RestResponse
     */
    @ApiOperation(value = "修改机构", notes = "修改机构")
    @SysLog("修改机构")
    @PostMapping("/update")
   // @RequiresPermissions("sys:org:update")
    public RestResponse update(SysOrgEntity sysOrg) {
        if (sysOrg != null && sysOrg.getOrgNo() != null) {
            sysOrgService.update(sysOrg);
        }
        return RestResponse.success();
    }

    /**
     * 删除
     *
     * @param orgNo 机构编码
     * @return RestResponse
     */
    @ApiOperation(value = "删除机构", notes = "删除机构")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "orgNo", value = "机构编码", dataType = "String")
    })
    @SysLog("删除机构")
    @PostMapping("/delete")
    //@RequiresPermissions("sys:org:delete")
    public RestResponse delete(String orgNo) {
        orgNo = orgNo.replaceAll("\"", "");
        List<SysOrgEntity> sysOrgEntities = sysOrgService.queryListByOrgNo(orgNo);
        if (sysOrgEntities.size() > 0) {
            return RestResponse.error("请先删除子机构");
        } else {
            sysOrgService.delete(orgNo);
        }
        return RestResponse.success();
    }
    

    /**
     * 查询机构类型
     *
     * @param code 查询参数
     * @return RestResponse
     */
    @ApiOperation(value = "查询机构类型", notes = "查询机构类型")
    @PostMapping("/queryOrgType")
    public RestResponse queryOrgType() {
    	String orgType="";
    	List<SysDictEntity> result = new ArrayList<SysDictEntity>();
    	SysOrgEntity sysOrgEntity = this.getOrg();
    	SysUserEntity sysUserEntity = this.getUser();
    	
    	//运维单位用户没有机构id
    	if(StringUtil.isEmpty(sysUserEntity.getOrgNo())) {
    		orgType="6";
    	}
    	//项目机构登陆后没有机构对象
    	else if(null==sysOrgEntity) {
    		orgType="10";
    	}else {
    		orgType = sysOrgEntity.getOrgType();
    	}
    	
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("code", "MENU_ORG_TYPE");
        List<SysDictEntity> list = sysDictService.queryByCode(params);
        
        //只过滤当前登录用户的机构类型
        for(SysDictEntity dict : list) {
        	if(orgType.equals(dict.getValue())) {
        		result.add(dict);
        	}else if("6".equals(orgType)) {
        		result.add(dict);
        	}
        }        
        
        return RestResponse.success().put("list", result).put("type", "机构类型");
    }
}
